package com.sec.etech.bpm.cust.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sec.etech.bpm.cust.mapper.EtechTaskOpinionExtMapper;
import com.sec.etech.bpm.cust.model.EtechTaskOpinionExt;
import com.sec.etech.org.service.EtechUserUtil;
import com.sec.etech.sys.cal.service.WorkCalService;
import com.sec.etech.sys.util.DbUtil;
import lombok.extern.slf4j.Slf4j;
import org.openbpm.base.core.util.StringUtil;
import org.openbpm.bpm.api.engine.action.cmd.TaskActionCmd;
import org.openbpm.bpm.api.engine.plugin.context.BpmPluginContext;
import org.openbpm.bpm.api.engine.plugin.def.UserAssignRule;
import org.openbpm.bpm.api.model.def.IBpmDefinition;
import org.openbpm.bpm.api.model.nodedef.BpmNodeDef;
import org.openbpm.bpm.api.model.task.IBpmTask;
import org.openbpm.bpm.api.service.BpmTaskExtService;
import org.openbpm.bpm.core.manager.BpmDefinitionManager;
import org.openbpm.bpm.core.manager.BpmTaskManager;
import org.openbpm.bpm.core.manager.TaskIdentityLinkManager;
import org.openbpm.bpm.core.model.BpmTask;
import org.openbpm.bpm.core.model.BpmTaskOpinionExt;
import org.openbpm.bpm.core.model.TaskIdentityLink;
import org.openbpm.bpm.engine.action.cmd.DefualtTaskActionCmd;
import org.openbpm.bpm.plugin.node.userassign.context.UserAssignPluginContext;
import org.openbpm.bpm.service.DefaultBpmTaskExtServiceImpl;
import org.openbpm.bus.api.model.IBusinessData;
import org.openbpm.org.api.model.IGroup;
import org.openbpm.org.api.model.IUser;
import org.openbpm.org.api.service.GroupService;
import org.openbpm.org.api.service.UserService;
import org.openbpm.org.core.manager.GroupManager;
import org.openbpm.org.core.model.Group;
import org.openbpm.sys.api.model.DefaultIdentity;
import org.openbpm.sys.api.model.SysIdentity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * Etech流程任务定制属性服务
 * 扩展流程任务记录属性bpm_task_opinion并兼容新旧流程系统
 */
@Slf4j
@Service
@ConditionalOnProperty(prefix = "bpm.bpm-ext", name = "task-ext", havingValue = "cust")
public class EtechTaskExtServiceImpl extends DefaultBpmTaskExtServiceImpl implements BpmTaskExtService {


    @Resource(name = "etechUserService")
    private UserService userService;

    @Resource(name="etechGroupService")
    private GroupService groupService;

    @Autowired
    private GroupManager groupManager;

    @Resource
    BpmDefinitionManager bpmDefinitionManager;

    @Resource
    private EtechTaskOpinionExtMapper taskOpinionExtMapper;

    @Autowired
    FlowSpecialCheckService flowSpecialCheckHelper;

    @Resource
    BpmTaskManager bpmTaskManager;

    @Resource
    TaskIdentityLinkManager taskIdentityLinkManager;


    @Override
    public void onTaskCreate(TaskActionCmd taskActionModel, BpmNodeDef nodeDef) {
        BpmTask task = (BpmTask) taskActionModel.getBpmTask();

        EtechTaskOpinionExt taskOpinionExt = taskOpinionExtMapper.selectById(getTaskOpinionByTaskId(task.getTaskId()).getId());

        JSONObject defProps = getDefProperties2(taskActionModel);

        // 1. 增强扩展属性(通用，冗余）
        enhanceTaskOpinionExt(taskOpinionExt, taskActionModel, nodeDef);


        // 2. 流程扩展属性/节点扩展属性用于定制逻辑
        JSONObject nodeProps = null;
        if (nodeDef != null) {
            nodeProps = nodeDef.getNodeProperties();
        }

        // 设置节点控制编号
        try{
            setNodeControllNum(taskOpinionExt, nodeDef);
        }catch (Exception e){
            log.error("设置TaskOpinion节点控制编号失败", e);
        }


        // 2.1 检查候选人以及并设置主管组/部门
        try{
            setMasterGroupInTaskOpinion(taskOpinionExt, nodeProps, task, taskActionModel);
        }catch (Exception e){
            log.error("设置TaskOpinion责任部门失败", e);
        }


        // 2.2 工作日天数/剩余工作日天数/过期时间
        try{
            setWorkdaysInTaskOpinion(taskOpinionExt, nodeProps, taskActionModel);
        }catch (Exception e){
            log.error("设置TaskOpinion工作天数/预期完成时间失败", e);
        }

        // 定制TODO子平台连接
        String custTodoListName = null;
        String custTodoListUrl = null;
        if (StringUtil.isEmpty(custTodoListName)) {
            if (defProps != null && defProps.containsKey("custTodoListName")) {
                custTodoListName = defProps.getString("custTodoListName");
            }
        }
        if (StringUtil.isEmpty(custTodoListUrl)) {
            if (defProps != null && defProps.containsKey("custTodoListUrl")) {
                custTodoListUrl = defProps.getString("custTodoListUrl");
            }
        }
        // 替换 ${xx}
        if (StringUtil.isNotEmpty(custTodoListUrl)) {
            Map map = new HashMap();
            map.putAll(taskActionModel.getVariables());
            map.put("instId", task.getInstId());
            map.put("taskId", task.getTaskId());
            custTodoListUrl = parse(custTodoListUrl, map);
        }

        String strExtData = task.getExtData();
        // url or [title](url)  or {"title":"xxx","url":"/xxx/yyy"}
        if (StringUtil.isNotEmpty(custTodoListUrl)) {
            strExtData = custTodoListUrl;
            if (StringUtil.isNotEmpty(custTodoListName)) {
                //strExtData = "[" + custTodoListName + "](" + custTodoListUrl + ")";
                strExtData = custTodoListUrl+ "#" + custTodoListName;
            }
        }
        if (StringUtil.isNotEmpty(strExtData)) {
            task.setExtData(strExtData);
            saveBpmTask(task);
        }

        // 补充业务数据(月度报表所需数据准备)
        try{
            enhanceTaskData(taskOpinionExt, taskActionModel, defProps, nodeProps);
        }catch (Exception e){
            log.warn("enhanceBusData fail", e);
        }


        // 保存扩展信息
        taskOpinionExt.setUpdateTime(new Date());

        taskOpinionExtMapper.updateById(taskOpinionExt);
        taskOpinionExt = taskOpinionExtMapper.selectById(taskOpinionExt.getId());  //fix

        try{
            flowSpecialCheckHelper.onTaskCreate(taskActionModel, nodeDef, taskOpinionExt);
        }catch (Exception e){
            // TODO 如何抛出异常？
            log.warn(" flowSpecialCheckHelper.onTaskCreate fail", e);
        }
    }


    protected static String parse(String content, Map<String, Object> kvs) {
        Matcher m = regex.matcher(content);
        StringBuffer sr = new StringBuffer();
        while (m.find()) {
            String group = m.group();
            group = group.substring(2, group.length() - 1);
            m.appendReplacement(sr, String.valueOf(kvs.get(group)));
        }
        m.appendTail(sr);
        return sr.toString();
    }

    protected static Pattern regex = Pattern.compile("\\$\\{(.*?)\\}");

    protected JSONObject getDefProperties2(TaskActionCmd taskActionModel) {
        JSONObject defProps = null;
        try{
            IBpmDefinition bpmDefinition = null;
            if(((DefualtTaskActionCmd) taskActionModel).getBpmDefinition()!=null){
                bpmDefinition = ((DefualtTaskActionCmd) taskActionModel).getBpmDefinition();
            }else{
                bpmDefinition = bpmDefinitionManager.get(taskActionModel.getDefId());
            }
            defProps = JSONObject.parseObject(bpmDefinition.getDefSetting()).getJSONObject("flow").getJSONObject("properties");

        }catch (Exception e){
            log.warn("getDefProperties error, "+e.getMessage());
        }
        return defProps;
    }

    @Override
    public void onTaskAssign(IBpmTask task) {
        BpmTaskOpinionExt taskOpinion = getTaskOpinionExtByTaskId(task.getTaskId());

    }

    @Override
    public void onTaskComplete(TaskActionCmd taskActionModel) {
        EtechTaskOpinionExt taskOpinionExt = this.getTaskOpinionExtByAction(taskActionModel);
        // 增加 任务完成的定制逻辑检查
        try{
            flowSpecialCheckHelper.onTaskComplete(taskActionModel, taskOpinionExt);
        }catch (Exception e){
            // TODO 如何抛出异常？
            log.warn(" flowSpecialCheckHelper.onTaskComplete fail {} > {} > {}", e.getMessage(), e.toString(),
                    Arrays.stream(e.getStackTrace()).map(a -> a.toString()).collect(Collectors.joining("\n")));
        }

        taskOpinionExt = taskOpinionExtMapper.selectById(taskOpinionExt.getId());

        // 检查完成是否及时
        // 完成时间
        // 是否超期，超期原因
        taskOpinionExt.setRealCompleteDay(new Date());
        if(taskOpinionExt.getPlanCompleteDay()!=null){
            // 在预期完成时间之前完成则及时
            if(DateUtil.compare(taskOpinionExt.getRealCompleteDay(), WorkCalService.endOfDay(taskOpinionExt.getPlanCompleteDay()))<0){
                taskOpinionExt.setIsIntTime(1);
            }else {
                taskOpinionExt.setIsIntTime(0);
            }
        }

        // 保存扩展信息
        taskOpinionExt.setUpdateTime(new Date());
        taskOpinionExtMapper.updateById(taskOpinionExt);

    }

    @Override
    public void preTaskComplete(TaskActionCmd taskActionModel) {
        log.debug("preTaskComplete");
        EtechTaskOpinionExt taskOpinionExt = this.getTaskOpinionExtByAction(taskActionModel);
        //throw new BusinessException("throw preTaskComplete exception");
        flowSpecialCheckHelper.preTaskComplete(taskActionModel, taskOpinionExt);
    }

    @Override
    public void postTaskComplete(TaskActionCmd taskActionModel) {
        log.debug("postTaskComplete");
        //throw new BusinessException("throw postTaskComplete exception");
    }


    protected void setNodeControllNum(EtechTaskOpinionExt taskOpinionExt, BpmNodeDef nodeDef){
        // 检查控制编号
        String nodeControlNum = "";
        List<BpmPluginContext> plugins =  nodeDef.getBpmPluginContexts();
        if(plugins!=null){
            for(BpmPluginContext pluginContext: plugins){
                if(pluginContext instanceof UserAssignPluginContext){
                    List<UserAssignRule> rules =((UserAssignPluginContext)pluginContext).getBpmPluginDef().getRuleList();
                    if(rules!=null){
                        for(UserAssignRule rule: rules){
                            String ruleDesc = rule.getDescription();
                            int index = ruleDesc.indexOf("[脚本]");
                            if(index>0){
                                nodeControlNum = ruleDesc.substring(index+4).trim();
                                if(nodeControlNum.endsWith(";")){
                                    // fix
                                    nodeControlNum = nodeControlNum.substring(0, nodeControlNum.length()-1);
                                }
                                break;
                            }
                        }
                    }
                }
                if(StringUtil.isNotEmpty(nodeControlNum)){
                    break;
                }
            }
        }
        if(StringUtil.isNotEmpty(nodeControlNum)){
            taskOpinionExt.setNodeControlNum(nodeControlNum);
        }
    }
    /**
     * 设置责任部门
     *
     * @param taskOpinionExt
     * @param nodeProps
     * @param task
     */
    public void setMasterGroupInTaskOpinion(EtechTaskOpinionExt taskOpinionExt, JSONObject nodeProps, BpmTask task, TaskActionCmd taskActionModel){
        // 检查候选人

        // 2.1 主管组/部门
        String masterGroupId = null;
        String masterGroupName = null;
        if (nodeProps != null && nodeProps.containsKey("masterGroupId")) {
            masterGroupId = nodeProps.getString("masterGroupId");
            masterGroupName = nodeProps.getString("masterGroupName");
            // fix 节点已配置责任部门的不再检查其他条件
            boolean isNum = false;
            try{
                isNum = NumberUtil.isInteger(masterGroupId);
            }catch (Exception e){
                isNum = false;
            }
            if(!isNum){
                // 临时处理 前端将masterGroupId同masterGroupName
                List<Map<String,Object>> list = DbUtil.getJdbcTemplate().queryForList("select id_ from org_group where name_=? order by path_ limit 1", masterGroupName);
                if(list!=null && list.size()>0){
                    masterGroupId = String.valueOf(list.get(0).get("id_"));
                }
            }
            taskOpinionExt.setMasterGroup(masterGroupId);
            taskOpinionExt.setMasterGroupName(masterGroupName);
            // return
        }

        //  增加检查是否为原PLANSign节点，需要特殊处理
        if(StringUtil.isEmpty(masterGroupId) && taskActionModel.getBizDataMap()!=null){
            boolean isPlanSignNode = false;
            // 取消控制编号的检查，只判断是否勾选 计划员处理 planSignNode
            // 先检查节点控制编号
//            if(taskOpinionExt.getNodeControlNum()!=null && ("plansign".equals(taskOpinionExt.getNodeControlNum().toLowerCase())
//            || "plan_sign".equals(taskOpinionExt.getNodeControlNum().toLowerCase()))){
//                isPlanSignNode = true;
//            }
            if (!isPlanSignNode && nodeProps != null && "1".equals(nodeProps.getString("planSignNode"))){
                isPlanSignNode = true;
            }

            if (isPlanSignNode){
                Map<String, IBusinessData> dataMap = taskActionModel.getBizDataMap();
                for(String key: dataMap.keySet()){
                    // 1 计划任务 - 设计科室
                    // 计划任务 plantask%  designdprtid
                    if(key.toLowerCase().startsWith("plantask")){
                        IBusinessData businessData = dataMap.get(key);
                        if(businessData.getData().containsKey("designdprtid")){

                            String designdprtid = String.valueOf(businessData.getData().get("designdprtid"));
                            if(StringUtil.isNotEmpty(designdprtid)){
                                masterGroupId = String.valueOf(EtechUserUtil.getEtechGroupService().getDprtidByDesigndprtid(Long.valueOf(designdprtid)));
                                if(StringUtil.isNotEmpty(masterGroupId)){
                                    Group group = groupManager.get(masterGroupId);
                                    masterGroupName = group.getGroupName();
                                    break;
                                }
                            }
                        }
                    }
                    // 2 修改单 - 所属科室
                    // 修改单 amend%  compileuserid
                    if(key.toLowerCase().startsWith("amend")){
                        IBusinessData businessData = dataMap.get(key);
                        if(businessData.getData().containsKey("compileuserid")){
                            String compileuserid = String.valueOf(businessData.getData().get("compileuserid"));
                            IGroup group = groupService.getMainGroup(compileuserid);
                            if(group!=null){
                                masterGroupId = group.getGroupId();
                                masterGroupName = group.getGroupName();
                            }
                            break;
                        }
                    }
                }
            }
        }

        String assigneeId = task.getAssigneeId();
        if(StringUtil.isEmpty(assigneeId) || "0".equals(assigneeId)){
            // 获取第一个处理人
            String assignInfo = taskOpinionExt.getAssignInfo();
            //user-周欣康-370,user-张琪-214,user-钱晨琳-798,
            if(StringUtil.isNotEmpty(assignInfo)){
                String[] assignUsers = assignInfo.split(",");
                for(String assignUser: assignUsers){
                    if(assignUser.startsWith("user-")){
                        assigneeId = assignUser.substring(assignUser.lastIndexOf("-")+1);
                        break;
                    }
                }
            }
            // 如果候选人为空，提供默认候选人
            // 流程错误处理人 角色 flow_handler 流程节点抓不到人时，将把此角色的人设置为该节点的处理人
            if(StringUtil.isEmpty(assigneeId)){
                List<IUser> users = EtechUserUtil.getUsersByRoleCode("flow_handler");
                if(users!=null && users.size()>0){
                    IUser user = users.get(0);
                    assigneeId = user.getUserId();
                    addTaskNodeUser(task.getTaskId(), user.getUserId(), user.getFullname());
                    taskOpinionExt.setAssignInfo(String.format("user-%S-%S",user.getFullname(), user.getUserId()));
                }
            }
            if(StringUtil.isEmpty(assigneeId)){
                // 换成流程管理员？
                // List<String> listAdmin = EtechUserUtil.getUserIdsByRoleCode("flow_admin");
                // 添加默认候选人  茂昌 1128

                //2021年1月14日14:43:14 去掉默认处理人
/*                addTaskNodeUser(task.getTaskId(), "1128", "彭茂昌");
                assigneeId = "1128";
                taskOpinionExt.setAssignInfo("user-彭茂昌-1128");*/
            }
        }
        if(StringUtil.isEmpty(masterGroupId)){
            // 获取第一个处理人的部门
            if(StringUtil.isNotEmpty(assigneeId)){
                IGroup group = groupService.getMainGroup(assigneeId);
                if(group!=null){
                    masterGroupId = group.getGroupId();
                    masterGroupName = group.getGroupName();
                }
            }
        }
        // 默认责任部门： STP技术管理处(id=7,code=4018)
        if (StringUtil.isEmpty(masterGroupId)) {
            masterGroupId = "7";
        }
        // fix
        if (StringUtil.isEmpty(masterGroupName)) {
            masterGroupName = "STP技术管理处";
        }


        if (StringUtil.isNotEmpty(masterGroupId)) {
            taskOpinionExt.setMasterGroup(masterGroupId);
        }
        if (StringUtil.isNotEmpty(masterGroupName)) {
            taskOpinionExt.setMasterGroupName(masterGroupName);
        }
    }

    public void setWorkdaysInTaskOpinion(EtechTaskOpinionExt taskOpinionExt, JSONObject nodeProps, TaskActionCmd taskActionModel){

        // 工作日天数/剩余工作日天数/过期时间
        // 如节点未配置工作天数则默认为当天
        int planWorkDay = 0;
        if (nodeProps.containsKey("planWorkDay")) {
            String strPlanWorkDay = nodeProps.getString("planWorkDay");
            strPlanWorkDay = EtechTaskExtServiceImpl.parse(strPlanWorkDay, taskActionModel.getVariables());
            try{
                planWorkDay = NumberUtil.parseInt(strPlanWorkDay);
            }catch (Exception e){

            }
        }
        // JOB 计算剩余时间也需要同步修改
        if (planWorkDay >= 0) {
            taskOpinionExt.setPlanWorkdays(planWorkDay);
            taskOpinionExt.setRemainDays(planWorkDay);
            taskOpinionExt.setCalDaysTime(new Date());
            Date planCompleteDay = workCalendarManager.getWorkDayByDays(new Date(), planWorkDay);
            if (planCompleteDay != null) {
                planCompleteDay = WorkCalService.endOfDay(planCompleteDay); //当天
                taskOpinionExt.setPlanCompleteDay(planCompleteDay);
            }
        }

        taskOpinionExtMapper.updateById(taskOpinionExt);

        // 定制中可能会 根据  "计划送审时间 => 预期完成时间" 重新设置 planCompleteDay
    }

    protected void enhanceTaskData(EtechTaskOpinionExt taskOpinionExt, TaskActionCmd taskActionModel, JSONObject defProps, JSONObject nodeProps) {
        // task记录业务平台的关联数据，用于报表统计

        // 所属子平台，计划任务/修改单/问题报告/采购ACC/通用流程中心
        // 平台：PLAN/DM/PR/ACC/SAM/BC
        // 优先级：已锁定/高/中/低
        // 平台

        // TODO defProps nodeProps代表着流程属性？？
        String busModule = null;
        if(defProps!=null && defProps.containsKey("busModule")){
            busModule = defProps.getString("busModule");
        }

        // 业务表/业务主键？

        // 只有部分节点需要考核，默认不考核
        // 考核属性:1-刚性考核/2-柔性考核/0-不考核
        int kpiType = 0;
        if (nodeProps!=null && nodeProps.containsKey("kpiType")) {
            kpiType = nodeProps.getInteger("kpiType");
        }
        taskOpinionExt.setKpiType(kpiType);

        // 优先级
        int busPriority = -1;
        // 统计分值Value（同优先级相关）
        int value = 0;

        // 编号
        String busTaskNo = null;
        // 名称
        String busTaskName = null;

        // 从业务表中抓取数据，假定表单关联的第一个业务对象的主业务对象
        IBusinessData businessData = null;
        Iterator<IBusinessData> it = taskActionModel.getBizDataMap().values().iterator();
        if (it.hasNext()) {
            businessData = it.next();
        }
        if (businessData != null) {
            String tableKey = businessData.getBusTableRel().getTableKey();
            Map mapBusData = businessData.getData();
            // 获取业务表的优先级
            try{
                busPriority = MapUtil.getInt(mapBusData, "priorityid");
            }catch (Exception e){
                try{
                    if(busPriority==-1) {
                        busPriority = MapUtil.getInt(mapBusData, "priority");
                    }
                }catch (Exception e1){
                }
            }

            // 未获取到所属平台信息，从业务数据中抓取
            if(StringUtil.isEmpty(busModule)){
                if ("proj_plantask".equalsIgnoreCase(tableKey)) {
                    // 计划任务PLAN
                    busModule = "PLAN";
                } else if ("proj_amend".equalsIgnoreCase(tableKey)) {
                    // 修改单 DM
                    busModule = "DM";
                } else if ("prod_pr".equalsIgnoreCase(tableKey)) {
                    // 问题报告 PR
                    busModule = "PR";
                } else if ("prod_acc".equalsIgnoreCase(tableKey)) {
                    // 采购ACC
                    busModule = "ACC";
                } else if("bpm_center".equalsIgnoreCase(tableKey) || "CHAIN_blueprint".equalsIgnoreCase(tableKey)
                        || "sam_mmd_metalBill".equals(tableKey) || "icm_interface_detail".equals(tableKey)){
                    busModule = "BC";
                } else if("E_sam_secs_ref_bpm".equalsIgnoreCase(tableKey)) {
                    busModule = "SAM";
                } else {
                    // 如无所属模块则保存关联业务表名
                    busModule = tableKey;
                }
            }
            if("PLAN".equalsIgnoreCase(busModule)){

                busTaskNo = MapUtil.getStr(mapBusData, "plantasknum");
                busTaskName = MapUtil.getStr(mapBusData, "plantaskname");

                if("proj_external_coordination".equalsIgnoreCase(tableKey)) {
                    // TODO 有问题的数据
                    busTaskNo = MapUtil.getStr(mapBusData, "externalCoordinationNum");
                    busTaskName = "计划调整流程";
                }else{
                    //85清单名称赋值

                    busTaskNo = MapUtil.getStr(mapBusData, "plantasknum");
                    busTaskName = MapUtil.getStr(mapBusData, "plantaskname");

                }

            }else if("DM".equalsIgnoreCase(busModule)){
                busTaskNo = MapUtil.getStr(mapBusData, "amendnum");
                busTaskName = MapUtil.getStr(mapBusData, "businessName");
                if(kpiType>0 && busPriority==-1){
                    try{
                        // 获取修改单优先级 proj_amend_bpe.priority
                        Map<String,Object> map2 = DbUtil.getJdbcTemplate().queryForMap("select t.priority from proj_amend_bpe t where t.amendid=?", MapUtil.getInt(mapBusData,"amendid"));
                        busPriority = MapUtil.getInt(map2, "priority");
                    }catch (Exception e){
                        log.warn("修改单"+busTaskNo+"获取优先级失败", e.getMessage());
                    }
                }
            }else if("PR".equalsIgnoreCase(busModule)){
                busTaskNo = MapUtil.getStr(mapBusData, "prnum");
                busTaskName = MapUtil.getStr(mapBusData, "sketch");
            }else if("ACC".equalsIgnoreCase(busModule)){
                busTaskNo = MapUtil.getStr(mapBusData, "accnum");
                busTaskName = MapUtil.getStr(mapBusData, "accname");
            }else if("SAM".equalsIgnoreCase(busModule)){
                busTaskNo = MapUtil.getStr(mapBusData, "bpmSubject");
                busTaskName = MapUtil.getStr(mapBusData, "samSecsName");
            }else if("BC".equalsIgnoreCase(busModule)){
                //System.out.println(mapBusData);
                if("bpm_center".equalsIgnoreCase(tableKey)) {
                    busTaskNo = MapUtil.getStr(mapBusData, "bcCode");
                    busTaskName = MapUtil.getStr(mapBusData, "bcTopic");
                }else if("CHAIN_blueprint".equalsIgnoreCase(tableKey)){
                    busTaskNo = MapUtil.getStr(mapBusData, "bpcode");
                    Long ordersId = MapUtil.getLong(mapBusData, "ordersid");
                    if(ordersId!=null && ordersId>0) {
                        String sql = "select orders,names from proj_project_orders where ordersid=?";
                        List<Map<String,Object>> list = DbUtil.getJdbcTemplate().queryForList(sql, ordersId);
                        if(list!=null && list.size()>0){
                            busTaskName = list.get(0).get("orders").toString() + " " + (list.get(0).get("names")!=null? list.get(0).get("names").toString(): "");
                        }
                    }
                }else if("sam_mmd_metalBill".equalsIgnoreCase(tableKey)){
                    busTaskNo = MapUtil.getStr(mapBusData, "identifier");
                    Map metalNum = businessData.getChild("sam_mmd_metalNum").get(0).getData();
                    if(metalNum!=null) {
                        busTaskName = metalNum.get("metalNumname").toString();
                    }
                }else if("icm_interface_detail".equalsIgnoreCase(tableKey)){
                    Map icmMap = businessData.getChild("icm_list").get(0).getData();
                    busTaskNo = icmMap.get("serialNumber").toString();
                    busTaskName = icmMap.get("detailedDescription").toString();
                }else {
                    busTaskNo = MapUtil.getStr(mapBusData, "serialNumber");
                    busTaskName = MapUtil.getStr(mapBusData, "theme");
                }
            }else if("SPP".equalsIgnoreCase(busModule)){
                busTaskNo = MapUtil.getStr(mapBusData, "num");
                busTaskName = MapUtil.getStr(mapBusData, "processname");
            }else if("planning_OrderListStorage".equals(taskOpinionExt.getDefKey())){
                busTaskNo = MapUtil.getStr(mapBusData, "ordersid");
                busTaskName = MapUtil.getStr(mapBusData, "orders");
            }else if("planning_ComponentStorage".equals(taskOpinionExt.getDefKey())){
                busTaskNo = MapUtil.getStr(mapBusData, "componentid");
                busTaskName = MapUtil.getStr(mapBusData, "componentnum");
            }else if("planning_ComponentStorage4Purchase".equals(taskOpinionExt.getDefKey())){
                busTaskNo = MapUtil.getStr(mapBusData, "componentid");
                busTaskName = MapUtil.getStr(mapBusData, "componentnum");
            }
        }

        // 平台
        if (StringUtil.isEmpty(taskOpinionExt.getBusModule()) && StringUtil.isNotEmpty(busModule)) {
            taskOpinionExt.setBusModule(busModule);
        }
        // KPI类型
        if(kpiType>=0){
            taskOpinionExt.setKpiType(kpiType);
        }
        busPriority = busPriority==-1? 0: busPriority;//优先级 默认普通
        // 优先级
        // TODO busPriority>=0 ??
        if ((taskOpinionExt.getBusPriority() == 0 || taskOpinionExt.getBusPriority() == -1) && busPriority >= 0) {
            taskOpinionExt.setBusPriority(busPriority);
        }
        // 设置分值
        // value 计算公式为：优先级为锁定的4分，优先级极高的为3分，高的为2分，普通为1分
        // 0-普通，1-高，2-极高，3-锁定
        if(kpiType>0){
            // 柔性任务
            if(kpiType==2){
                value=1;
            }
            // 刚性任务
            if(kpiType==1){
                if(busPriority>=0){
                    value = busPriority+1;
                }
            }
            taskOpinionExt.setValue(value);
        }
        if (StringUtil.isEmpty(taskOpinionExt.getBusTaskNo()) && StringUtil.isNotEmpty(busTaskNo)) {
            taskOpinionExt.setBusTaskNo(busTaskNo);
        }
        if (StringUtil.isEmpty(taskOpinionExt.getBusTaskName()) && StringUtil.isNotEmpty(busTaskName)) {
            taskOpinionExt.setBusTaskName(busTaskName);
        }
    }
    //通过TaskActionCmd获取EtechTaskOpinionExt
    private EtechTaskOpinionExt getTaskOpinionExtByAction(TaskActionCmd taskActionModel){
        BpmTask task = (BpmTask) taskActionModel.getBpmTask();
        EtechTaskOpinionExt taskOpinionExt = taskOpinionExtMapper.selectById(getTaskOpinionByTaskId(task.getTaskId()).getId());
        return taskOpinionExt;
    }


    /**
     * 任务处理节点增加处理人
     * @param taskId
     * @param uid
     * @return
     */
    public String addTaskNodeUser(String taskId, String uid, String userName){
        // 任务处理节点增加处理人
        if(taskId==null || uid==null) {return null;}
        try {
            BpmTask task = bpmTaskManager.get(taskId);
            List<TaskIdentityLink> list = taskIdentityLinkManager.getByTaskId(taskId);
            TaskIdentityLink link2 = null;
            if (list != null) {
                for (TaskIdentityLink link : list) {
                    if ("user".equals(link.getType())) {
                        if (link2 == null) {
                            link2 = link;
                        }
                        if (uid.equalsIgnoreCase(link.getIdentity())) {
                            return null;
                        }
                    }
                }
            }
            List<SysIdentity> taskIdentitys = new ArrayList<>();
            taskIdentitys.add(new DefaultIdentity(uid, userName, "user"));
            taskIdentityLinkManager.createIdentityLink(task, taskIdentitys);

            // 同步更新 bpm_task_opinion中处理人信息
            // update TaskOpinion assignInformation
            list = taskIdentityLinkManager.getByTaskId(taskId);
            taskIdentitys = new ArrayList<>();
            for(TaskIdentityLink identityLink: list){
                SysIdentity identity = new DefaultIdentity(identityLink.getType(), identityLink.getIdentity(), identityLink.getIdentityName());
                taskIdentitys.add(identity);
            }
            StringBuilder assignInfo = new StringBuilder();
            if (CollectionUtil.isNotEmpty(taskIdentitys)) {
                for (SysIdentity identity : taskIdentitys) {
                    assignInfo.append(identity.getType()).append("-").append(identity.getName()).append("-").append(identity.getId()).append(",");
                }
            }
            EtechTaskOpinionExt taskOpinionExt = taskOpinionExtMapper.selectOne(new LambdaQueryWrapper<EtechTaskOpinionExt>().eq(EtechTaskOpinionExt::getTaskId, taskId));
            if(taskOpinionExt!=null && assignInfo.length()>0){
                taskOpinionExt.setAssignInfo(assignInfo.toString());
                taskOpinionExtMapper.updateById(taskOpinionExt);
            }

            log.debug("任务处理节点增加处理人完成, taskId={}, userId={}", taskId, uid);
        }catch (Exception e){
            log.error("任务处理节点增加处理人失败, taskId={}, userId={}", taskId, uid);
        }
        return "success";
    }

}
